package org.example.mad.dao;

import org.example.mad.entity.Student;
import org.example.mad.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {
    public static final int PAGE_SIZE = 5; // 每页显示的数据条数
    public List<Student> getStudentsByPage(int pageNum) {
    List<Student> studentList = new ArrayList<>();
    String sql = "SELECT * FROM students LIMIT ?,?";
try (Connection connection = DBUtil.getConnection();
     PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
        int startIndex = (pageNum - 1) * PAGE_SIZE;
        preparedStatement.setInt(1, startIndex);
        preparedStatement.setInt(2, PAGE_SIZE);
        try (ResultSet resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                Student student = new Student();
                student.setId(resultSet.getInt("id"));
                student.setName(resultSet.getString("name"));
                student.setAge(resultSet.getInt("age"));
                studentList.add(student);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
return studentList;
}
// 可以根据需要添加其他方法，比如获取总记录数等
//这里定义了每页显示的记录数为 5 ，通过 LIMIT 关键字在SQL语句中实现分页查询，同时有一个获
//取总记录数的方法方便后续计算总页数等操作。
//三、业务逻辑层（Service层，可选但推荐）
//创建 StudentService 类来处理业务逻辑，调用 StudentDAO 中的方法，示例如下：
//四、Servlet层
//创建一个 StudentServlet 类来处理客户端请求，实现分页数据的获取并转发到相应的JSP页面展
//示，示例代码：
public int getTotalCount() {
    int count = 0;
    String sql = "SELECT COUNT(*) FROM students";
    try (Connection connection = DBUtil.getConnection();
         PreparedStatement preparedStatement = connection.prepareStatement(sql);
         ResultSet resultSet = preparedStatement.executeQuery()) {
        if (resultSet.next()) {
            count = resultSet.getInt(1);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return count;
}
}
